//
//  MessageTableViewController.m
//  yilutongxing
//
//  Created by ios-23 on 17/4/12.
//  Copyright © 2017年 YZE. All rights reserved.
//
#import <QMUITips.h>
#import "MessageTableViewController.h"
#import "MessageCell.h"
#import "RPCommentReply.h"
#import "TopicDetailViewController.h"
#import "TimeTools.h"

#define URL_GetCommentmessageT @"/api/comments/mine?page=0&size=1000&sort=createdDate,desc"
#define URL_GetCommentmessage @"/api/comments/mineoftopic?page=0&size=1000&sort=createdDate,desc"
#define URL_GetTopicdetail @"/api/topics/"
#define URL_ClearUnread @"/api/message-boxes/clearUnreadCount/COMMENT_MESSAGE"  //清除评论消息数

@interface MessageTableViewController ()
@property(nonatomic,strong) NSArray *replyArr;
@end

@implementation MessageTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"回复我的";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageCell" bundle:[NSBundle mainBundle]]
         forCellReuseIdentifier:@"messageCell"];
    UIView *v = [[UIView alloc]init];
    [v setBackgroundColor:[UIColor grayColor]];
    self.tableView.tableFooterView = v;
    //取消息
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_GetCommentmessage]
                                      parameters:nil
                                        delegate:self
                                      requestTag:1
                                    successBlock:^(id responseObject)
     {
         NSMutableArray *replyArr1 = [[RPCommentReply mj_objectArrayWithKeyValuesArrayAdd:responseObject] mutableCopy];
         [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:URL_GetCommentmessageT]
                                            parameters:nil
                                              delegate:self
                                            requestTag:2
                                          successBlock:^(id responseObject)
          {
              NSArray *replyArr2 = [RPCommentReply mj_objectArrayWithKeyValuesArrayAdd:responseObject];
              //去重
              NSEnumerator *en2 = [replyArr2 objectEnumerator];
              RPCommentReply *reply2;
              while (reply2 = [en2 nextObject]) {
                  NSEnumerator *en1 = [replyArr1 reverseObjectEnumerator];//逆序遍历,因为可能要做删除操作
                  RPCommentReply *reply1;
                  while (reply1 = [en1 nextObject]) {
                      if ([reply1.replyDto.id isEqualToNumber:reply2.replyDto.id]) {
                          [replyArr1 removeObject:reply1];
                      }
                  }
              }
              
              NSArray *replyArrAll = [replyArr1 arrayByAddingObjectsFromArray:replyArr2];
              self.replyArr = [replyArrAll sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                  RPCommentReply *l = (RPCommentReply*)obj1;
                  RPCommentReply *r = (RPCommentReply*)obj2;
                  return [TimeTools getDateFromUTC:l.createdDate] < [TimeTools getDateFromUTC:r.createdDate];
              }];
              [self.tableView reloadData];
          }];
     }];
    //清除未读评论数
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingString:URL_ClearUnread]
                                       parameters:nil
                                         delegate:self
                                       requestTag:3
                                     successBlock:^(id responseObject)
    {
        debugLog(@"成功清除未读评论数");
    }];
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RPCommentReply *reply = self.replyArr[indexPath.row];
    [[YZENetwork sharedInstace]getRequestWithUrl:[NSString stringWithFormat:@"%@%@%ld",BASE,URL_GetTopicdetail,reply.topicId]
                                      parameters:nil
                                        delegate:self
                                      requestTag:1
                                    successBlock:^(id responseObject)
    {
        BaseModel *topic = [BaseModel mj_objectWithKeyValuesAdd:responseObject];
        TopicDetailViewController *v = [TopicDetailViewController new];
        v.topicDetail = topic;
        UINavigationController *navi=[[UINavigationController alloc]initWithRootViewController:v];
        [self.navigationController presentViewController:navi animated:YES completion:nil];
    }];
    [QMUITips showLoadingInView:self.view hideAfterDelay:1];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.replyArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RPCommentReply *reply = self.replyArr[indexPath.row];
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"messageCell" forIndexPath:indexPath];
    [cell setAvatar:reply.userDto.avatar
               name:reply.userDto.firstName
        createdDate:reply.createdDate
              title:reply.topicName
            content:reply.content
            isReply:reply.replyDto!=nil];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

@end
